<?php
/**
 * MasterGroup控制器
 *
 * PHP version 5
 *
 * @package   Ecga
 * @author    sunfengming <sunfengming@ec3s.com>
 * @copyright 2010 Xingchangxinda Inc.
 * @version   SVN: $Id$
 */
namespace Project\Apps\Ecga\Controllers;


use \Project\Apps\Ecga\Models\UserModelException;
use \Project\Apps\Ecga\Models\UserGroupModelException;
use \Project\Apps\Ecga\Library\AdminAuth;
use \Project\Apps\Ecga\Models\UserGroup;
use \Project\Apps\Ecga\Models\Projects;
use \Project\Apps\Ecga\Controllers\Abstraction\EcgaController;
use \Framework\System\Helper\HttpResponse;
use \Framework\System\Helper\HttpRequest;
use \Framework\Controller\ControllerException;
use \Framework\Mapper\FieldException;
use \Framework\System\Helper\Mail;

/**
 * MasterGroup控制器
 *
 * PHP version 5
 *
 * @package   Ecga
 * @author    sunfengming <sunfengming@ec3s.com>
 * @copyright 2010 Xingchangxinda Inc.
 * @version   Release: <0.1>
 */
class MasterGroup extends EcgaController
{
    /**
     * 默认Action
     *
     * @param HttpRequest $request request
     *
     * @return void
     */
    public static function show($request)
    {
        $page = self::createPage();
        $page->setTitle('管理员分组列表');
        $pageNo = $request->get('page', 'int', 1);
        $userList = self::createDataList(UserGroup::getPageQuery())
            ->setCurrentPage($pageNo)
            ->orderBy('id', 'desc');

        $page->assign('list', $userList);
        $page->assign('uri', $request->uri);
        HttpResponse::output($page->render('usergrouplist'));
    }

    /**
     * 获取操作权限列表
     *
     * @return array 权限列表
     * @author sunfengming
     */
    private static function _getAuthOptions()
    {
        $authArray = AdminAuth::parseAuthFile();
        $result = array();
        foreach ($authArray as $key => $titles) {
            $result[$titles[0]][$key] = $titles[1];
        }
        return $result;
    }

    /**
     * 添加管理员分组
     *
     * @param HttpRequest $request HttpRequest对象
     *
     * @return void
     * @author sunfengming
     */
    public static function add($request)
    {
        $userGroupModel = model('UserGroup');
        $projectModel = model('Projects');
        $page = self::createPage();
        $page->setTitle('添加管理员分组');

        $page->assign('projectOptions', $projectModel->getProjectOptions());
        $page->assign('authOptions', self::_getAuthOptions());
        $page->assign('data', $userGroup);
        $page->assign('formHash', self::generateFormHash('doAdd'));
        HttpResponse::output($page->render('usergroupdetail'));
    }

    /**
     * 处理管理员分组添加表单提交
     *
     * @param HttpRequest $request HttpRequest对象
     *
     * @return void
     * @author sunfengming
     * @throws FieldException
     */
    public static function doAdd($request)
    {
        $formHash = $request->post('formHash', 'string');
        if (!self::validateFormHash('doAdd', $formHash)) {
            self::message('对不起，表单已过期，请您重新操作！', 'warning', './mastergroup.php?a=show');
        }

        $userGroupModel = model('UserGroup');
        $data = self::_getFormData($request);
        $userGroup =$userGroupModel->create();
        try {
            self::_save($userGroup, $data);
        } catch (ControllerException $e) {
            self::message($e->getMessage(), 'warning');
            self::add($request);
            return;
        }
        self::message(
            sprintf(
                '您已成功添加了管理员分组“%s”',
                $data['groupName']
            ), 'notice', './mastergroup.php?a=show'
        );
    }

    /**
     * 编辑用户分组权限
     *
     * @param HttpRequest $request HttpRequest Instance
     *
     * @throws ControllerException
     *
     * @return void
     * @author sunfengming
     */
    public static function edit($request)
    {
        $userGroupModel = model('UserGroup');
        $projectModel = model('Projects');
        $id = $request->get('id', 'int');
        $userGroup = $userGroupModel->get($id);
        if ($userGroup === null) {
            throw new ControllerException('对不起，您要编辑的管理员分组不存在！');
        }
        if (1 == $userGroup->id) {
            throw new ControllerException('对不起，此管理员分组为系统内建，不能编辑！');
        }
        $allowProjects = explode(',', $userGroup->allowProjects);
        $allowControlArray = unserialize($userGroup->allowControls);
        if (!is_array($allowControlArray)) {
            $allowControlArray = array();
        }
        foreach ($allowControlArray as $allowControl) {
            $allowControls[] = implode('-', $allowControl);
        }
        $page = self::createPage();
        $page->setTitle('修改管理员分组');

        $page->assign('projectOptions', $projectModel->getProjectOptions());
        $page->assign('allowProjects', $allowProjects);
        $page->assign('allowControls', $allowControls);
        $page->assign('authOptions', self::_getAuthOptions());
        $page->assign('data', $userGroup);
        $page->assign('id', $id);
        $page->assign('formHash', self::generateFormHash('doEdit'));
        HttpResponse::output($page->render('editusergroupdetail'));
    }

    /**
     * ORM修改用户分组权限
     *
     * @param HttpRequest $request HttpRequest Instance
     *
     * @throws ControllerException
     *
     * @return void
     * @author sunfengming
     */
    public static function doEdit($request)
    {
        $id = $request->post('id', 'int');
        $formHash = $request->post('formHash', 'string');
        if (!self::validateFormHash('doEdit', $formHash)) {
            self::message('对不起，表单已过期，请您重新操作！', 'warning', './master.php?a=show');
        }

        $userGroupModel = model('UserGroup');
        $data = self::_getFormData($request, true);
        $userGroup = $userGroupModel->get($id);
        if ($userGroup === null) {
            throw new ControllerException('对不起，您要编辑的管理员分组不存在！');
        }
        if (1 == $userGroup->id) {
            throw new ControllerException('对不起，此管理员分组为系统内建，不能编辑！');
        }
        $data['groupName'] = $userGroup->groupName;
        try {
            self::_save($userGroup, $data);
        } catch (ControllerException $e) {
            self::message($e->getMessage(), 'warning');
            self::add($request);
            return;
        }

        self::message(
            sprintf(
                '您已成功修改了管理员分组“%s”的信息。',
                $data['groupName']
            ), 'notice', './mastergroup.php?a=show'
        );
    }

    /**
     * 保存管理员分组信息
     *
     * @param Entity $entity 管理员实体
     * @param array  $data   需要保存的管理员信息
     *
     * @return void
     * @throws ControllerException FieldException
     * @author sunfengming
     */
    private static function _save ($entity, $data)
    {
        try {
            $entity->setAttributes($data)->save();
        } catch (FieldException $e) {
            switch ($e->getCode()) {
            case FieldException::BLANK_VALUE :
                if ($e->field == 'groupName') {
                    $message = '对不起，管理员分组名称不能为空。';
                } elseif ($e->field == 'allowProjects') {
                    $message = '对不起，可管理项目不得为空。';
                } else {
                    throw $e;
                }
                break;
            case FieldException::UNIQUE_VALUE :
                if ($e->field == 'siteId,groupName') {
                    $message = '对不起，管理员分组名称已存在。';
                } else {
                    throw $e;
                }
                break;
            case FieldException::INVALUD_VALUE :
                    throw $e;
                break;
            default:
                throw $e;
            }
            throw new ControllerException($message);
        }
    }

    /**
     * 删除管理员分组
     *
     * @param HttpRequest $request HttpRequest对象
     *
     * @return void
     * @author sunfengming
     */
    public static function remove($request)
    {
        $userGroupModel = model('UserGroup');
        $id = $request->post('id', 'int');
        $userGroup = $userGroupModel->get($id);
        if ($userGroup === null) {
            HttpResponse::jsonWarning('对不起，您要删除的管理员分组不存在！');
            return;
        }
        $groupName = $userGroup->groupName;
        try {
            self::_drop($userGroup);
        } catch (UserGroupModelException $e) {
            HttpResponse::jsonWarning($e->getMessage());
        }
    }

    /**
     * 批量删除管理员分组
     *
     * @param HttpRequest $request HttpRequest对象
     *
     * @return void
     * @author sunfengming
     */
    public static function batchRemove($request)
    {
        $userGroupModel = model('UserGroup');
        $ids = $request->post('id', 'array');
        foreach ($ids as $id) {
            $userGroup = $userGroupModel->get($id);
            if ($userGroup === null) {
                continue;
            }
            $userGroup = $userGroup->groupName;
            try {
                self::_drop($userGroup);
            } catch (UserGroupModelException $e) {
                self::message($e->getMessage(), 'warning');
                continue;
            }
            self::message(sprintf('您已成功删除了管理员分组“%s”。', $userGroup));
        }
        HttpResponse::redirect($request->referer);
    }

    /**
     * 删除管理员分组
     *
     * @param Entity $userGroup 管理员分组对象
     *
     * @return void
     * @throws ControllerException
     * @author sunfengming
     */
    private static function _drop($userGroup)
    {
        $userGroup->delete();
    }



    /**
     * 得到表单数据
     *
     * @param HttpRequest $request HttpRequest对象
     * @param bool        $isEdit  是否是修改
     *
     * @return array
     * @author Blue5tar
     */
    private static function _getFormData($request, $isEdit = false)
    {
        $allowControls = $request->post('allowControls', 'array');
        if (empty($allowControls)) {
            throw new ControllerException('权限不得为空！');
        }
        $allowControlArray = array();
        foreach ($allowControls as $allowControl) {
            $allowControlArray[] = explode('-', $allowControl);
        }
        //后台必要控制器权限默认给出
        $allowControlArray[] = array('index', '*');
        $allowControlArray[] = array('profile', '*');
        $allowControlArray[] = array('productsearch', '*');
        $allowControlArray[] = array('table', 'export', '*');
        if (!$isEdit) {
            return array(
                'groupName'      => $request->post('groupName', 'string'),
                'allowProjects' => implode(',', $request->post('allowProjects', 'array')),
                'allowControls' => serialize($allowControlArray)
            );
        } else {
            return array(
                'allowProjects' => implode(',', $request->post('allowProjects', 'array')),
                'allowControls' => serialize($allowControlArray)
            );
        }
    }

}